#include "Config.h"
#include "Debug.h"
#include <iostream>
#include <fstream>

using namespace std;

const char CConfig::CONFIG_DELIMITER[] = "=";

const char *CConfig::CONFIG_TABLE[CE_MAXENTRY] = {
  "configfile",	//CE_CONFIGFILE
  "lowsipport",	//CE_LOWSIPPORT
  "sipportsize",	//CE_SIPPORTSIZE
  "lowrtpport",	//CE_LOWRTPPORT
  "rtpportsize",	//CE_RTPPORTSIZE
  "codec",	//CE_CODEC
  "rtmp_addr",  //CE_RTMP_ADDR
  "rtp_addr",   //CE_RTP_ADDR
  "sip_addr"    //CE_SIP_ADDR
};

const char *CConfig::CONFIG_DEFAULT[CE_MAXENTRY] = {
  "/etc/rtmp_daemon.conf",	//CE_CONFIGFILE
  "50000",			//CE_LOWSIPPORT
  "1000",       //CE_SIPPORTSIZE
  "51000",			//CE_LOWRTPPORT
  "1000",       //CE_RTPPORTSIZE
  "speex",			//CE_CODEC
  "",                           //CE_RTMP_ADDR
  "",                           //CE_RTP_ADDR
  ""                            //CE_SIP_ADDR
};

CConfig::CConfig()
{
  for(int i = 0; i < CE_MAXENTRY; i++) {
    m_strConfs[i] = CONFIG_DEFAULT[i];
  }
}

CConfig::~CConfig()
{

}

bool CConfig::Init(const char *szFile)
{
  m_strConfs[CE_CONFIGFILE] = szFile;
  return ParseFile();
}

bool CConfig::ParseFile()
{
  const char *_szFile = m_strConfs[CE_CONFIGFILE].c_str();
  ifstream _ifs(_szFile);
  if(!_ifs.is_open())
    return false;

  DBGMSG("conf file: \'%s\' start parsing", _szFile);
  // alluseful lines comes in format:^name = value$
  string _strLine;
  size_t _uiPos;
//string _strName, _strValue;

  while(getline(_ifs, _strLine)) {
    if(_ifs.eof() || _ifs.fail())
      break;
    if(_strLine.length() <= 0)
      continue;

    DBGMSG("conf file: line read: \'%s\'", _strLine.c_str());
    _uiPos = _strLine.find(CONFIG_DELIMITER);
    if(_uiPos == string::npos || _strLine.find(CONFIG_DELIMITER, _uiPos + 1) != string::npos) {
      DBGMSG("Warning: conf file: \'%s\' incorrect syntax: \'%s\'", _szFile, _strLine.c_str());
      continue;
    }
    const string &_strName = _strLine.substr(0, _uiPos);
    const string &_strValue = _strLine.substr(_uiPos + sizeof(CONFIG_DELIMITER) - 1);
    DBGMSG("conf file: name: \'%s\'", _strName.c_str());
    DBGMSG("conf file: value: \'%s\'", _strValue.c_str());

    int i;
    for(i = 0; i < CE_MAXENTRY; i++) {
      if(_strName.compare(CONFIG_TABLE[i]) == 0) {
        DBGMSG("conf file: config index: \'%d\'", i);
        break;
      }
    }
    if(i == CE_MAXENTRY) {
      DBGMSG("Warning: conf file: \'%s\' unknown variable: \'%s\'", _szFile, _strName.c_str());
      continue;
    }
    
    m_strConfs[i] = _strValue;
  }
  _ifs.close();
  DBGMSG("conf file: \'%s\' finish parsing", _szFile);
  return true;
}
